/*
 * Copyright 2008-2023 dexian.vip. All rights reserved.
 * Support: http://www.dexian.vip
 * License: http://www.dexian.vip/license
 */

package vip.dexian.core.base.validation;

import cn.hutool.core.util.PhoneUtil;
import jakarta.validation.ConstraintValidator;
import jakarta.validation.ConstraintValidatorContext;
import org.apache.commons.lang3.StringUtils;


/**
 * 手机号码校验
 *
 * @author 挺好的 2023年05月30日 15:36
 */
public class MobileValidator implements ConstraintValidator <Mobile, String> {

    /**
     * 是否必填
     */
    private boolean isRequired;

    /**
     * 初始化操作，此处对于手机号码设置为必填
     *
     * @param constraintAnnotation
     *         约束注解
     */
    @Override
    public void initialize (Mobile constraintAnnotation) {
        this.isRequired = constraintAnnotation.required();
    }

    /**
     * 实现校验逻辑，要注意线程安全
     *
     * @param value
     *         object to validate
     * @param context
     *         context in which the constraint is evaluated
     *
     * @return 如果格式不正确，返回false
     */
    @Override
    public boolean isValid (String value, ConstraintValidatorContext context) {

        if (this.isRequired) {
            if (StringUtils.isBlank(value)) {
                return false;
            }
        } else {
            if (value == null) {
                return true;
            }
        }

        if (value.length() != 11) {
            return false;
        }

        return PhoneUtil.isMobile(value);
    }
}
